import React, {useState, useEffect} from "react";
import {Form, Modal, Button, Card, Spin, Tabs, Row, Col, message} from "antd";
import NextNodeSelect from "components/flowdataDetail/NextNodeSelect";
import {openNotificationWithIcon} from 'utils/comm';
import _remove from 'lodash/remove';


import UsersTags from "../usersTags/UsersTags";

import styles from "./NextNodeForm.less";

const {TabPane} = Tabs;

const NextNodeForm = (props) => {

  const {
    onCancel,
    taskId,
    nextTaskDetailData: taskList = [],
    dispatch,
    visible,
    getList,
    processInstanceId,
    nextNodeLoading,
    forcePickIndex,
    forcePickComplete,
  } = props;

  const [targetKeys, setTargetKeys] = useState({});
  const [nodeIndex, setNodeIndex] = useState(0);
  const [taskDetail, setTaskDetail] = useState(taskList.length > 0 ? taskList[0] : {
    nodeCode: '', nodeName: '', dataTypeList: [],
  });
  const {nodeCode, fromNodeCode = '', nodeName, dataTypeList: treeData} = taskDetail;
  const [dataTypeList, setDataTypeList] = useState([]);
  const [candidateSetNull, setCandidateSetNull] = useState(false);
  const [treeSource, setTreeSource] = useState([]);
  const [selectOptions, setSelectOptions] = useState([]);

  const [treeCheckedKeys, setTreeCheckedKeys] = useState([])
  // const [checkedKeys, setCheckedKeys] = useState({});
  // const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [submitList, setSubmitList] = useState([]);

  const [selectType, setSelectType] = useState('');


  const typeSet = {
    STA: "人员",
    ORG: "组织",
    ROL: "角色",
    POSITION: '岗位',
    GROUP: '用户组',
    FUNCTION: "自定义函数",
    RELATIONSHIP: '关系',
  };


  useEffect(() => {
    dispatch({
      type: "FlowHandle/getNextTaskDetail",
      payload: taskId,
    });
  }, []);


  useEffect(() => {

    // const tmpTreeData = treeData.map(item => {
    // let {flowTaskCandidateInfoVos = []} = item;
    // const {dataType} = item;

    // if (dataType !== 'STA') {
    //   flowTaskCandidateInfoVos = flowTaskCandidateInfoVos.map(subItem => {
    //     return {
    //       ...subItem,
    //     }
    //   })
    // }
    //   return {dataType, flowTaskCandidateInfoVos};
    // })
    //
    // setDataTypeList(tmpTreeData);
    setDataTypeList(treeData);

  }, [treeData])

  useEffect(() => {
    setNodeIndex(forcePickIndex);
  }, [forcePickIndex]);


  useEffect(() => {
    if (!taskList || taskList.length === 0) {
      return;
    }

    const detail = taskList[nodeIndex];

    setTaskDetail(detail)
    const tmpType = detail?.dataTypeList?.length > 0 ? detail.dataTypeList[0].dataType : 'STA';
    setSelectType(tmpType);

    // 是否是空数据
    const tmpCandidateSetNull = detail?.candidateSetNull && detail?.candidateSetNull === '1';
    setCandidateSetNull(tmpCandidateSetNull);

    if (nodeIndex < submitList.length) {

      const {
        targetKeys: _targetKeys = {},
        // checkedKeys: _checkedKeys = {},
        selectOptions: _selectOptions = [],
      } = submitList[nodeIndex];

      setTargetKeys(_targetKeys);
      // setCheckedKeys(_checkedKeys);
      setSelectOptions(_selectOptions);
    } else {

      const {dataTypeList: dataTypeList1 = []} = detail ?? {};

      // 默认全选
      // const tmpChecked = {};
      const tmpTarget = {};
      const tmpOptions = [];

      // 空数据首次展示不全选
      if (tmpCandidateSetNull) {
        setTargetKeys(tmpTarget);
        // setCheckedKeys(tmpChecked);
        setSelectOptions(tmpOptions);
        return;
      }

      // 回显
      // const tmpCheckedRe = {};
      const tmpTargetRe = {};
      const tmpOptionsRe = [];

      // 是否是回显的标记
      let isBack = false;
      dataTypeList1.map(item => {
        const {dataType, flowTaskCandidateInfoVos = []} = item;

        // const tmpCheckedList = tmpChecked[dataType] ?? [];
        const tmpTargetList = tmpTarget[dataType] ?? [];

        // const tmpCheckedListRe = tmpCheckedRe[dataType] ?? [];
        const tmpTargetListRe = tmpTargetRe[dataType] ?? [];

        flowTaskCandidateInfoVos.map(subItem => {
          // tmpCheckedList.push(subItem.code);
          tmpTargetList.push({key: subItem.code, ...subItem});
          tmpOptions.push({key: subItem.code, ...subItem});
          if (subItem?.isPick && subItem?.isPick === '1') {
            // tmpCheckedListRe.push(subItem.code);
            tmpTargetListRe.push({key: subItem.code, ...subItem});
            tmpOptionsRe.push({key: subItem.code, ...subItem});
            isBack = true;
          }
          return subItem;
        })
        // tmpChecked[dataType] = tmpCheckedList;
        tmpTarget[dataType] = tmpTargetList;

        // tmpCheckedRe[dataType] = tmpCheckedListRe;
        tmpTargetRe[dataType] = tmpTargetListRe;

        return item;
      })

      if (isBack) {
        setTargetKeys(tmpTargetRe);
        // setCheckedKeys(tmpCheckedRe);
        setSelectOptions(tmpOptionsRe);
      } else {
        setTargetKeys(tmpTarget);
        // setCheckedKeys(tmpChecked);
        setSelectOptions(tmpOptions);
      }
    }

  }, [nodeIndex, taskList]);

  useEffect(() => {
    const tmpList = dataTypeList.find((item) => item.dataType === selectType);

    let tmpTreeSource = tmpList?.flowTaskCandidateInfoVos ?? [];
    tmpTreeSource = tmpTreeSource.map(item => {
      return {key: item.code, ...item};
    })

    setTreeSource(tmpTreeSource)

  }, [selectType, dataTypeList]);

  useEffect(() => {
    const tmpList = selectOptions.map(item => {
      return item?.key ?? item.code;
    });
    setTreeCheckedKeys(tmpList);
  }, [selectOptions]);


  const handleOk = () => {

    if (!selectOptions || selectOptions.length === 0) {
      message.warning('请选择至少一位办理人');
      return;
    }

    const nodeCandidateTaskDTOList = [];

    selectOptions.map(item => {
      const {code, name, type: dataType} = item;
      nodeCandidateTaskDTOList.push({
        fromNodeCode,
        nodeCode,
        dataType,
        name,
        code,
      })
      return item;
    })

    // const tmpKeys = Object.keys(targetKeys);
    //
    // tmpKeys.map(dataType => {
    //   const list = targetKeys[dataType];
    //
    //   list.map(subItem => {
    //     const {code, name, type = dataType} = subItem;
    //     nodeCandidateTaskDTOList.push({
    //       fromNodeCode,
    //       nodeCode,
    //       dataType: type,
    //       name,
    //       code,
    //     })
    //     return subItem;
    //   })
    //
    //   return dataType;
    // })


    const userCode = sessionStorage.getItem("USER_CODE") ?? '';
    dispatch({
      type: "FlowHandle/postNextNodeAssignee",
      payload: {taskId, nodeCandidateTaskDTOList, userCode, comment: ''},
    }).then(({errCode, errMsg}) => {
      if (errCode === 0) {
        if (nodeIndex === taskList.length - 1) {
          onCancel(false);
          getList();

          openNotificationWithIcon("success", "", "指定成功");

          if (forcePickComplete && (forcePickComplete instanceof Function)) {
            forcePickComplete();
          }
        }
      } else {
        openNotificationWithIcon("error", "", errMsg);
      }
    })

  }


  const handleNext = () => {

    if (!selectOptions || selectOptions.length === 0) {
      message.warning('请选择至少一位办理人');
      return;
    }

    const tmpItem = {
      targetKeys,
      // checkedKeys,
      selectOptions,
      comment: '',
    }
    submitList.splice(nodeIndex, 1, tmpItem);
    setSubmitList(submitList);


    handleOk();


    const tmpIndex = nodeIndex + 1;
    setNodeIndex(tmpIndex);
  }
  const handlePre = () => {
    const tmpIndex = nodeIndex - 1;
    setNodeIndex(tmpIndex);
  }

  const handleAdd = (type, source = []) => {

    const list = source.map(item => {
      const {key, code, name} = item;

      return {key, code, name, type:item.type};
    })

    const tmpTarget = targetKeys;
    const tmpTargetList = tmpTarget[type] ?? [];


    tmpTarget[type] = unionArray([...tmpTargetList, ...list]);

    setTargetKeys(tmpTarget);


    // const tmpList = _unionWith(selectOptions, list, _isEqual);

    // const tmpList = _unionBy([...selectOptions, ...list], ['code', 'type']);

    const tmpList = unionArray([...selectOptions, ...list]);

    if (list.length > 0 && tmpList.length === selectOptions.length) {
      const {name} = list[0];
      message.warning(`${name}已在选中的列表中`);
      return;
    }
    setSelectOptions(tmpList);
  }

  const unionArray = (list=[]) => {
    const tmpList = [];
    const tmpKeys = [];
    list.map(item => {

      const key = `${item.code}-${item.type}`;

      if (tmpKeys.indexOf(key) === -1) {
        tmpList.push({...item});
        tmpKeys.push(key);
      }

      return item;
    })

    return tmpList;
  }

  // 删除项 ---- 这里有问题
  const handleDelSelect = (delList = []) => {

    const allKeys = Object.keys(targetKeys);

    delList.map(delItem => {
      const {code = ''} = delItem || {};

      _remove(selectOptions, (e) => e.code === code && e.type === delItem.type);

      allKeys.map(type => {
        const tmpTargets = targetKeys[type] ?? [];
        _remove(tmpTargets, (e) => e.code === code && e.type === delItem.type)
        targetKeys[type] = [...tmpTargets];
        return type;
      })
      return delItem;
    })

    setTargetKeys({...targetKeys});
    setSelectOptions([...selectOptions])

  }


  const setOrgList = (type, list) => {
    dataTypeList.map(item => {
      if (item.dataType === type) {
        item.flowTaskCandidateInfoVos = list;
      }
      return item;
    })

    setDataTypeList([...dataTypeList])
  }

  const handleClear = () => {
    setSelectOptions([]);
    setTargetKeys({})
  }


  return (
    <Modal
      title="指定后续节点处理人"
      visible={visible}
      onOk={handleOk}
      onCancel={() => onCancel(false)}
      width="850px"
      className={styles.root}
      centered
      closable={false}
      maskClosable={false}
      hideRequiredMark
      labelAlign="center"
      confirmLoading={nextNodeLoading}
      footer={[
        (taskList.length > 1 && nodeIndex > 0 ? (
          <Button
            key="pre"
            loading={nextNodeLoading}
            type="primary"
            onClick={handlePre}
          >
            上一节点
          </Button>
        ) : null),
        <Button
          key="ok"
          loading={nextNodeLoading}
          type="primary"
          onClick={taskList.length === 1 || nodeIndex === taskList.length - 1 ? handleOk : handleNext}
        >
          {taskList.length === 1 || nodeIndex === taskList.length - 1 ? '确定' : '下一节点'}
        </Button>,

      ]}
    >

      <Spin spinning={nextNodeLoading}>
        <Card
          size="small"
          title={
            <div
              style={{width: '100%', display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}
            >
              <span>{`节点名称: ${nodeName}`}</span>
              <span>{`${nodeIndex + 1} / ${taskList.length}`}</span>
            </div>
          }
        >
          <Row gutter={24}>
            <Col span={16}>
              <Tabs
                defaultActiveKey={selectType}
                activeKey={selectType}
                onChange={(activeKey) => setSelectType(activeKey)}
              >
                {dataTypeList.map((item) => {
                  const {dataType} = item;
                  const tabTitle = typeSet[dataType] ?? '';
                  return (
                    <TabPane key={dataType} tab={tabTitle} />
                  )
                })}
              </Tabs>


              <NextNodeSelect
                key={selectType}
                setOrgList={setOrgList}
                type={selectType}
                dispatch={dispatch}
                handleAdd={handleAdd}
                processInstanceId={processInstanceId}
                treeSource={treeSource}
                // changeTreeSource={changeTreeSource}
                candidateSetNull={candidateSetNull}
                handleDelSelect={handleDelSelect}
                treeCheckedKeys={treeCheckedKeys}
              />


            </Col>

            <Col span={8}>
              <div style={{
                width: '100%',
                height: '100%',
                margin: '10px 0px',
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'end',
              }}
              >
                <Button size='small' onClick={handleClear}>清空</Button>
              </div>


              <div className={styles.user_list}>
                <div style={{display: 'flex', flexDirection: 'column'}}>
                  {selectOptions.map(item => (
                    <UsersTags
                      key={`${item.type}_${item.code}`}
                      label={item.name}
                      onClick={() => handleDelSelect([item])}
                    />
                  ))}
                </div>

              </div>
            </Col>

          </Row>

        </Card>

        {/*  暂时隐藏
          <div className={styles.opinion}>意见</div>
          <Form.Item label="">
            {getFieldDecorator("comment", {
              rules: [
                {max: 200, message: "请不要超过200个字符"},
              ],
            })(
              <TextArea
                placeholder="请输入意见，最大限制在200个字数内"
                rows={5}
              />
            )}
          </Form.Item>
          */}

      </Spin>

    </Modal>
  );
}

export default Form.create()(NextNodeForm);

